import { userRoles, userRolesUpdate } from '@/services/userRole';

const defaultModal = {
  visible: false,
  data: {},
};

export default {
  namespace: 'userRole',

  state: {
    user: {},
    list: [],
    selectRoleKeys: [],
    modal: { ...defaultModal },
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const { data } = yield call(userRoles, payload);
      const selectRoleKeys = [];
      data.forEach(element => {
        if (element.isSelected) {
            selectRoleKeys.push(element.roleId);
        }
    });
      yield put({
        type: 'list',
        payload: {list: data, selectRoleKeys }
      });
    },
    *update({ payload }, { call, put, select }) {
      const user = yield select(state => state.userRole.user);
      const params = { roleIds: payload.selectRoleKeys, userId: user.userId}
      yield put({
        type: 'selectRoleKeys',
        payload
      });
      return yield call(userRolesUpdate, params);
    },
    *openModal({ payload }, { put }) {
      yield put({
        type: 'modal',
        payload: {
          data: payload || {},
          visible: true,
        },
      });
    },
    *closeModal(_, { put }) {
      yield put({
        type: 'modal',
        payload: { ...defaultModal },
      });
    },

  },

  reducers: {
    user(state, { payload }) {
      return { ...state, user: payload };
    },
    list(state, { payload }) {
      return { ...state, ...payload };
    },
    selectRoleKeys(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
